package com.kelab.dify.service;

import com.kelab.dify.config.DifyConfig;
import com.kelab.dify.exception.DifyException;
import com.kelab.dify.service.base.BaseService;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 文件服务类
 * 提供文件上传和管理功能
 * 
 * @author kelab
 * @version 1.0
 */
public class FileService extends BaseService {
    
    private static final Logger logger = LoggerFactory.getLogger(FileService.class);
    
    private static final String FILES_UPLOAD_ENDPOINT = "files/upload";
    private static final String FILES_ENDPOINT = "files";
    
    /**
     * 构造函数
     * 
     * @param httpClient HTTP客户端
     * @param objectMapper JSON映射器
     * @param config 配置信息
     */
    public FileService(OkHttpClient httpClient, ObjectMapper objectMapper, DifyConfig config) {
        super(httpClient, objectMapper, config);
    }
    
    /**
     * 上传文件
     * 
     * @param file 要上传的文件
     * @param user 用户标识
     * @return 上传响应
     * @throws DifyException 如果上传失败
     */
    public FileUploadResponse uploadFile(java.io.File file, String user) throws DifyException {
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(file, MediaType.parse("application/octet-stream")))
                .addFormDataPart("user", user)
                .build();
        
        Request request = new Request.Builder()
                .url(config.getFullUrl(FILES_UPLOAD_ENDPOINT))
                .post(body)
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, FileUploadResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to upload file", e);
        }
    }
    
    /**
     * 上传文件（通过字节数组）
     * 
     * @param fileData 文件数据
     * @param fileName 文件名
     * @param user 用户标识
     * @return 上传响应
     * @throws DifyException 如果上传失败
     */
    public FileUploadResponse uploadFile(byte[] fileData, String fileName, String user) throws DifyException {
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName,
                        RequestBody.create(fileData, MediaType.parse("application/octet-stream")))
                .addFormDataPart("user", user)
                .build();
        
        Request request = new Request.Builder()
                .url(config.getFullUrl(FILES_UPLOAD_ENDPOINT))
                .post(body)
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, FileUploadResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to upload file", e);
        }
    }
    
    /**
     * 获取文件信息
     * 
     * @param fileId 文件ID
     * @return 文件信息响应
     * @throws DifyException 如果请求失败
     */
    public FileInfoResponse getFileInfo(String fileId) throws DifyException {
        String url = config.getFullUrl(FILES_ENDPOINT + "/" + fileId);
        
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, FileInfoResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to get file info", e);
        }
    }
    
    /**
     * 删除文件
     * 
     * @param fileId 文件ID
     * @return 删除响应
     * @throws DifyException 如果删除失败
     */
    public FileDeleteResponse deleteFile(String fileId) throws DifyException {
        String url = config.getFullUrl(FILES_ENDPOINT + "/" + fileId);
        
        Request request = new Request.Builder()
                .url(url)
                .delete()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, FileDeleteResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to delete file", e);
        }
    }
    
    /**
     * 获取文件列表
     * 
     * @param user 用户标识
     * @param page 页码（可选）
     * @param limit 每页数量（可选）
     * @return 文件列表响应
     * @throws DifyException 如果请求失败
     */
    public FilesResponse getFiles(String user, Integer page, Integer limit) throws DifyException {
        StringBuilder urlBuilder = new StringBuilder(config.getFullUrl(FILES_ENDPOINT));
        urlBuilder.append("?user=").append(user);
        
        if (page != null && page > 0) {
            urlBuilder.append("&page=").append(page);
        }
        if (limit != null && limit > 0) {
            urlBuilder.append("&limit=").append(limit);
        }
        
        Request request = new Request.Builder()
                .url(urlBuilder.toString())
                .get()
                .addHeader("Authorization", config.getAuthorizationHeader())
                .build();
        
        try (Response response = httpClient.newCall(request).execute()) {
            return handleResponse(response, FilesResponse.class);
        } catch (IOException e) {
            throw new DifyException("Failed to get files", e);
        }
    }
    
    // 内部响应类定义
    public static class FileUploadResponse {
        private String id;
        private String name;
        private String size;
        private String extension;
        private String mimeType;
        private String createdBy;
        private Long createdAt;
        
        // Getter和Setter方法
        public String getId() {
            return id;
        }
        
        public void setId(String id) {
            this.id = id;
        }
        
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
        
        public String getSize() {
            return size;
        }
        
        public void setSize(String size) {
            this.size = size;
        }
        
        public String getExtension() {
            return extension;
        }
        
        public void setExtension(String extension) {
            this.extension = extension;
        }
        
        public String getMimeType() {
            return mimeType;
        }
        
        public void setMimeType(String mimeType) {
            this.mimeType = mimeType;
        }
        
        public String getCreatedBy() {
            return createdBy;
        }
        
        public void setCreatedBy(String createdBy) {
            this.createdBy = createdBy;
        }
        
        public Long getCreatedAt() {
            return createdAt;
        }
        
        public void setCreatedAt(Long createdAt) {
            this.createdAt = createdAt;
        }
    }
    
    public static class FileInfoResponse {
        // 根据实际API响应结构定义字段
    }
    
    public static class FileDeleteResponse {
        // 根据实际API响应结构定义字段
    }
    
    public static class FilesResponse {
        // 根据实际API响应结构定义字段
    }
}